<template>
  <div>
    <div class="app-container">
      <el-form
        ref="formEl"
        :rules="rules"
        :model="from"
        class="app-form"
        label-width="120px"
      >
        <el-form-item label="产品名称" prop="modelName">
          <el-input
            v-model="from.modelName"
            max="24"
            placeholder="请填写产品名称"
          />
        </el-form-item>
        <el-form-item label="产品类别" prop="product_auditDescription">
          <!-- 级联选择器 -->
          <el-cascader
            style="width: 500px"
            v-model="from.product_auditDescription"
            :options="treeOptions"
            :props="{
              checkStrictly: true,
              label: 'dictName',
              value: 'id',
              children: 'children',
            }"
            clearable
          />
        </el-form-item>

        <el-form-item label="产品型号" prop="marking">
          <el-input v-model="from.marking" max="24" placeholder="请填写型号" />
        </el-form-item>
        <el-form-item label="产品编码" prop="modelCode">
          <el-input
            v-model="from.modelCode"
            max="24"
            placeholder="请填写编码"
          />
        </el-form-item>
        <el-form-item label="尺寸规格" prop="specifications">
          <el-input
            v-model="from.specifications"
            max="24"
            placeholder="请填写尺寸规格"
          />
        </el-form-item>
        <!-- 区域选择 -->
        <el-form-item label="区域" prop="province">
          <el-cascader
            v-model="from.province"
            :options="areaList"
            :props="{
              label: 'name',
              value: 'id',
              children: 'children',
            }"
            clearable
          />
        </el-form-item>
        <el-form-item label="标准体系" prop="standard">
          <el-radio-group v-model="from.standard">
            <el-radio label="叠合剪力墙" />
            <el-radio label="钢结构" />
            <el-radio label="灌浆套筒" />
            <el-input v-model="from.standard" placeholder="自定义输入" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="预览图片" prop="shrinkageChart">
          <!-- <UploadImg
            :limit="6"
            :lableName="'authorizationLetter'"
            @upload="receiveFile"
            :imgUrl="imgUrl"
          /> -->
          <div class="uploadimg" :style="{ marginLeft: marginLeft }">
            <el-upload
              action="false"
              accept="image/png,image/gif,image/jpg,image/jpeg"
              :limit="6"
              :with-credentials="true"
              multiple
              list-type="picture-card"
              :before-upload="beforeUpload"
              v-model:file-list="imgfileList"
              :http-request="httpRequest"
              :on-preview="handlePictureCardPreview"
              :on-remove="onRemove"
            >
              <div class="uploadIco">
                <i class="el-icon-plus"></i>
                <div class="text">上传图片</div>
              </div>
            </el-upload>
            <el-dialog
              v-model="imgdialogVisible"
              width="600px"
              append-to-body
              class="uploadimgDialog"
            >
              <img style="width: 500px; height: 500px" :src="dialogImageUrl" />
            </el-dialog>
          </div>
        </el-form-item>

        <el-form-item label="案例模型" prop="modelFileDtos">
          <el-row>
            <el-col :span="24">
              <div>
                <el-cascader
                  v-model="from.modelFileDtos"
                  :options="modelTypeList"
                  :props="{
                    label: 'value',
                    value: 'id',
                    children: 'children',
                  }"
                  clearable
                />
              </div>
            </el-col>
            <el-col :span="24" style="margin-top: 20px">
              <UploadFile
                :limit="3"
                :lableName="'authorizationLetter'"
                @upload="uploadFileChange"
                :accept="'.rfa'"
                :fileLists="ModelfileList"
              ></UploadFile
            ></el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="附件" prop="databaseModelFileDtos">
          <UploadFile
            :limit="3"
            :lableName="'annex'"
            @upload="annexFileChange"
            :accept="''"
            :fileLists="attachmentFileNames"
          ></UploadFile>
        </el-form-item>
      </el-form>
    </div>
    <div class="bottom-btn">
      <el-button @click="returnPage">取消</el-button>
      <el-button type="primary" @click="submit">提交</el-button>
    </div>
    <el-dialog
      :title="`新增${type == 1 ? '专业' : '分类'}`"
      v-model="dialogVisible"
      width="30%"
    >
      <el-form
        :model="dialogForm"
        ref="dialogFormRef"
        label-width="120px"
        :rules="dialogFormRules"
      >
        <el-form-item :label="type == 1 ? '专业' : '分类'" prop="dictName">
          <el-input v-model="dialogForm.dictName" style="width: 300px" />
        </el-form-item>
        <el-form-item label="编码" prop="dictValue">
          <el-input v-model="dialogForm.dictValue" style="width: 300px" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="submitData(type)"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import UploadFile from "@/components/Upload/UploadFileNew";
import { useRouter, useRoute } from "vue-router";
import useBuildlibraryStore from "@/store/modules/buildlibrary";
import {
  getDickAllTreeListRequest,
  queryProvince,
  uploadFileRequest,
  getModelDetailByIdRequest,
  getDeteilImgByIdRequest,
  changeFileRequest,
  getModelTypeListRequest,
} from "@/api/buildlibrary";
import { ref, reactive, onMounted } from "vue";
import { rules } from "./rules";
const router = useRouter();
const route = useRoute();

const from = reactive({
  modelName: "", //产品名称
  product_auditDescription: "", //多级分类 类别
  marking: "", //产品型号
  modelCode: "", //产品编码'
  specifications: "", //尺寸规格
  province: [], //区域0:省  1:市
  standard: "", //标准体系
  shrinkageChart: [], //图片列表

  modelFileDtos: [], //模型列表选择
  modelFileDtosFile: [], //模型上传文件列表
  databaseModelFileDtos: [], //附件列表
});

const {
  query: { pid, id },
} = route;
if (pid) {
  from.product_auditDescription = pid.split(",").map(Number) || [];
}

const ModelfileList = ref(null);
const attachmentFileNames = ref(null);
const info = ref(null);
let backimgids = ref([]);
let backimgnames = ref([]);
const getModelDetailById = async (id) => {
  const res = await getModelDetailByIdRequest({ id });
  info.value = res.data;
  //回显数据
  from.modelName = res.data.modelName;
  from.product_auditDescription = res.data.treeCode.split(",").map(Number);
  from.marking = res.data.marking;
  from.modelCode = res.data.modelCode;
  from.specifications = res.data.specifications;
  from.province = [parseInt(res.data.provinceId), parseInt(res.data.cityId)];
  from.standard = res.data.standard;
  from.modelFileDtos = [res.data.bigType, res.data.smallType].map(Number);

  //图片回显处理
  let imgids = res.data.shrinkageChartFileIds.split(","); //['123','234']
  backimgids.value = imgids;
  let imgnames = res.data.shrinkageChartFileNames.split(","); //['1.jpg','2.jpg']
  backimgnames.value = imgnames;
  let imgs = [];

  for (let i = 0; i < imgids.length; i++) {
    let res = await getDeteilImgByIdRequest(imgids[i]);
    let blob = new Blob([res]);
    let url = window.URL.createObjectURL(blob);
    imgs.push({
      url,
      id: imgids[i],
      name: imgnames[i],
    });
  }
  console.log(imgs);

  imgfileList.value = imgs;

  ModelfileList.value = {
    name: res.data.modelFileNames,
  };
  attachmentFileNames.value = {
    name: res.data.attachmentFileNames,
  };

  from.shrinkageChart = res.data.shrinkageChartFileIds; //图片
  from.modelFileDtosFile = res.data.modelFileIds; //模型
  from.databaseModelFileDtos = res.data.attachmentFileIds; //附件

  console.log(res);
};

onMounted(() => {
  // 获取多级菜单
  getTreeList();
  //获取地区
  getAreaList();
  //获取模型分类
  getModelTypeList();
  if (id) {
    console.log(id);
    console.log("编辑模式");
    getModelDetailById(id);
  } else {
    console.log("新增模式");
  }
});

//获取多级分类
const treeOptions = ref([]);
const getTreeList = async () => {
  const res = await getDickAllTreeListRequest({ level: 5 });
  treeOptions.value = res.data;
  console.log(res);
};

//获取地区列表
const areaList = ref([]);
const getAreaList = async () => {
  const res = await queryProvince();
  areaList.value = res;
  console.log(res);
};

//获取模型分类
const modelTypeList = ref([]);
const getModelTypeList = async () => {
  const res = await getModelTypeListRequest({ model: { type: 0 } });
  console.log(res);
  modelTypeList.value = res.data.records;
  // console.log(modelType.data);
};

//图片选择钩子
// const receiveFile = (data) => {
//   from.shrinkageChart = data.fileArr;
//   console.log(data);
// };
//案例模型上传逻辑
const uploadFileChange = (data) => {
  from.modelFileDtosFile = data.fileArr;
  console.log(data);
};
//附件上传逻辑
const annexFileChange = (data) => {
  from.databaseModelFileDtos = data.fileArr;
  console.log(data);
};

const formEl = ref(null);
//提交表单逻辑
const submit = () => {
  formEl.value.validate(async (valid, fields) => {
    console.log(valid, fields);

    if (valid) {
      //判断是新增还是编辑
      if (!id) {
        const lastcode =
          from.product_auditDescription[
            from.product_auditDescription.length - 1
          ];
        console.log(from);
        const formData = new FormData();
        formData.append("attachmentFiles", from.databaseModelFileDtos[0]); //附件
        formData.append("bigType", from.modelFileDtos[0]); //案例大模型
        formData.append("cityId", from.province[1]); //市
        formData.append("currentTreeCode", lastcode);
        formData.append(
          "currentTreeName",
          getLastOptionName(lastcode, treeOptions.value)
        );
        formData.append("marking", from.marking);
        formData.append("modelCode", from.modelCode);
        formData.append("modelFiles", from.modelFileDtosFile[0]);
        formData.append("modelName", from.modelName);
        formData.append("provinceId", from.province[0]); //省

        from.shrinkageChart.forEach((item) => {
          formData.append("shrinkageChart", item); //图片
        });

        formData.append("smallType", from.modelFileDtos[1]); //小模型
        formData.append("specifications", from.specifications);
        formData.append("standard", from.standard);
        formData.append("treeCode", from.product_auditDescription.join(","));

        console.log(formData);
        for (let [a, b] of formData.entries()) {
          console.log(a, ":", b);
        }

        const res = await uploadFileRequest(formData);
        console.log(res);
        useBuildlibraryStore().message = res.message;
        useBuildlibraryStore().modelName = from.modelName;
        router.push({
          path: "/buildlibrary/modelclass",
          // params: { message: res.message, modelName: from.modelName },
        });
      } else {
        console.log("编辑逻辑", id);
        const lastcode =
          from.product_auditDescription[
            from.product_auditDescription.length - 1
          ];
        console.log(from);
        const formData = new FormData();

        formData.append("id", id);
        if (typeof from.databaseModelFileDtos === "string") {
          //附件
          //没有更改 把附件文件名和文件id传回去
          formData.append(
            "attachmentFileNames",
            info.value.attachmentFileNames
          );
          formData.append("attachmentFileIds", info.value.attachmentFileIds);
        } else {
          formData.append("attachmentFiles", from.databaseModelFileDtos[0]); //附件
        }

        formData.append("bigType", from.modelFileDtos[0]); //案例大模型
        formData.append("cityId", from.province[1]); //市
        formData.append("currentTreeCode", lastcode);

        formData.append(
          "currentTreeName",
          getLastOptionName(lastcode, treeOptions.value)
        );
        formData.append("marking", from.marking);
        formData.append("modelCode", from.modelCode);

        if (typeof from.modelFileDtosFile === "string") {
          //模型
          formData.append("modelFileIds", info.value.modelFileIds);
          formData.append("modelFileNames", info.value.modelFileNames);
        } else {
          formData.append("modelFiles", from.modelFileDtosFile[0]);
        }

        formData.append("modelName", from.modelName);
        formData.append("provinceId", from.province[0]); //省

        if (typeof from.shrinkageChart === "string") {
          //缩略图
          formData.append(
            "shrinkageChartFileNames",
            backimgnames.value.join(",")
          );
          formData.append("shrinkageChartFileIds", backimgids.value.join(","));
        } else {
          formData.append(
            "shrinkageChartFileNames",
            backimgnames.value.join(",")
          );
          formData.append("shrinkageChartFileIds", backimgids.value.join(","));

          from.shrinkageChart.forEach((item) => {
            formData.append("shrinkageChart", item);
          });
        }
        formData.append("smallType", from.modelFileDtos[1]); //小模型
        formData.append("specifications", from.specifications);
        formData.append("standard", from.standard);
        formData.append("treeCode", from.product_auditDescription.join(","));

        console.log(formData);
        for (let [a, b] of formData.entries()) {
          console.log(a, ":", b);
        }

        const res = await changeFileRequest(formData);
        console.log(res);
        useBuildlibraryStore().message = res.message;
        useBuildlibraryStore().modelName = from.modelName;
        router.push({
          path: "/buildlibrary/modelclass",
        });
      }
    } else {
      console.log(fields);
    }
  });
};

//根据id获取最后一个选项名称
const getLastOptionName = (id, list) => {
  let lastOptionName = "";
  //递归循环list
  const loop = (list) => {
    list.forEach((item) => {
      if (item.id === id) {
        lastOptionName = item.dictName;
      } else {
        if (item.children) {
          loop(item.children);
        }
      }
    });
  };
  loop(list);
  return lastOptionName;
};

const imgfileList = ref([]);
const fileArr = ref([]);
let imgdialogVisible = ref(false);
let dialogImageUrl = ref("");
//图片上传限制大小
const beforeUpload = (file) => {
  const isJPG =
    file.type === "image/jpeg" ||
    file.type === "image/png" ||
    file.type === "image/jpg" ||
    file.type === "image/gif";
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isJPG) {
    this.$Message.error("上传图片只能是 png、gif、jpeg、jpg 格式!");
  } else if (!isLt2M) {
    this.$Message.error("上传图片大小不能超过 2MB!");
  }
  return isJPG && isLt2M;
};
//
const httpRequest = (file) => {
  fileArr.value.push(file.file);
  let obj = {
    fileArr: fileArr.value,
    type: "add",
  };
  console.log(obj);
  from.shrinkageChart = obj.fileArr;
};
//预览
const handlePictureCardPreview = (file) => {
  imgdialogVisible.value = true;
  dialogImageUrl.value = file.url;
};
//删除
const onRemove = (file, fileList) => {
  let arr = [];
  console.log(file.id);
  let newlist = backimgids.value.filter((item) => {
    if (item != file.id) {
      return item;
    }
  });
  let newlist2 = backimgnames.value.filter((item) => {
    if (item != file.name) {
      return item;
    }
  });
  backimgids.value = newlist;
  backimgnames.value = newlist2;
  console.log(newlist);

  // fileList.forEach((item) => {
  //   if (item.raw) {
  //     arr.push(item.raw);
  //   } else {
  //     arr.push(item);
  //   }
  // });
  console.log(arr);
  // this.fileArr = arr;
  // this.$emit("upload", {
  //   fileArr: this.fileArr,
  //   type: "del",
  //   lableName: this.lableName,
  // });
};

//取消按钮
const returnPage = () => {
  router.go(-1);
};
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  justify-content: center;
  height: calc(100vh - 164px);
  overflow: auto;
}

::v-deep .app-form {
  width: 80%;
  margin: 20px;

  .el-form-item__label {
    font-weight: 700;
  }
}

.bottom-btn {
  width: 100%;
  height: 80px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-top: 1px solid #eee;

  .el-button {
    width: 100px;
  }
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.uploadimg {
  .uploadIco {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    line-height: 17px !important;
  }
}
::v-deep .disabled .el-upload {
  display: none;
}
</style>
